#include <iostream>
#include <string>
#include <strings.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#include<functional>
#include"Log.hpp"
#include"InetAddr.hpp"

using namespace LogModule;

using func_t = std::function<std::string(const std::string&,InetAddr&)>;

const int defaultfd = -1;
class UdpServer
{
public:
    UdpServer(uint16_t port,func_t func)
        : _sockfd(defaultfd), _port(port),_isrunning(false),_func(func)
    {
    }

    void Init()
    {
        //创建套接字
        _sockfd = socket(AF_INET,SOCK_DGRAM,0);
        if(_sockfd<0)
        {
            LOG(LogLevel::FATAL)<<"socket error";
            exit(1);
        }
        LOG(LogLevel::INFO)<<"socket succcess,sockfd:"<<_sockfd;

        //绑定socket信息，IP和端口
        struct sockaddr_in local;
        bzero(&local,sizeof(local));//将内存区域清0
        local.sin_family = AF_INET;
        local.sin_port = htons(_port);//主机字节序转化为网络字节序（大端）
        //ip也是如此，IP转成4字节，4字节转化成网络序列
        //local.sin_addr.s_addr = inet_addr(_ip.c_str());
        local.sin_addr.s_addr = INADDR_ANY;

        //服务端为什么要显示绑定，因为IP和端口号必须是众所周知的且不能轻易改变
        int n = bind(_sockfd,(struct sockaddr*)&local,sizeof(local));
        if(n<0)
        {
            LOG(LogLevel::FATAL)<<"bind error";
            exit(2);
        }

        LOG(LogLevel::INFO)<<"bind success,sockfd:"<<_sockfd;

    }

    void Start()
    {
        _isrunning = true;
        while(_isrunning)
        {
            char buffer[1024];
            struct sockaddr_in peer;
            socklen_t len = sizeof(peer);
            //1.收信息，client向服务端发信息就是希望服务端处理数据
            ssize_t s =  recvfrom(_sockfd,buffer,sizeof(buffer)-1,0,(struct sockaddr*)&peer,&len);//ppeer输出参数
            if(s>0)
            {
               InetAddr client(peer);
                std::string peer_ip = inet_ntoa(peer.sin_addr);//4字节风格的IP->点分十进制风格的IP

                buffer[s] = 0;
                std::string result = _func(buffer,client);

                //LOG(LogLevel::DEBUG)<<"["<<peer_ip<<":"<<peer_port<<"]"<<buffer;//消息内容以及谁发的

                //2.发信息
                std::string echo_string = "server echo@ ";
                echo_string+=buffer;
                sendto(_sockfd,result.c_str(),result.size(),0,(struct sockaddr*)&peer,len);

            }
           
        }
    }

    ~UdpServer()
    {
        
    }

private:
    int _sockfd;
    uint16_t _port;
    std::string _ip; // 点分十进制
    bool _isrunning;
    func_t _func;//服务器的回调函数，用于进行数据处理
};